import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

/**
 * 设置读取器类
 * 负责读取.vscode/settings.json中的css.helper配置
 */
export class SettingsReader {
    private workspaceRoot: string | undefined;

    constructor() {
        this.workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
    }

    /**
     * 获取CSS类名前缀列表
     * @returns 前缀字符串数组
     */
    public getPrefixes(): string[] {
        const config = vscode.workspace.getConfiguration('css.helper');
        return config.get<string[]>('prefix', []);
    }

    /**
     * 获取CSS文件路径列表
     * @returns CSS文件路径字符串数组
     */
    public getStyleSheets(): string[] {
        const config = vscode.workspace.getConfiguration('css.helper');
        return config.get<string[]>('styleSheets', []);
    }

    /**
     * 读取工作区.vscode/settings.json文件
     * @returns 设置对象或null
     */
    public readWorkspaceSettings(): any | null {
        if (!this.workspaceRoot) {
            return null;
        }

        const settingsPath = path.join(this.workspaceRoot, '.vscode', 'settings.json');
        
        try {
            if (fs.existsSync(settingsPath)) {
                const settingsContent = fs.readFileSync(settingsPath, 'utf8');
                return JSON.parse(settingsContent);
            }
        } catch (error) {
            console.error('读取.vscode/settings.json失败:', error);
        }

        return null;
    }

    /**
     * 从工作区设置中获取CSS前缀
     * @returns 前缀字符串数组
     */
    public getPrefixesFromWorkspace(): string[] {
        const settings = this.readWorkspaceSettings();
        if (settings && settings['css.helper'] && settings['css.helper'].prefix) {
            return settings['css.helper'].prefix;
        }
        return [];
    }

    /**
     * 从工作区设置中获取样式表路径
     * @returns 样式表路径字符串数组
     */
    public getStyleSheetsFromWorkspace(): string[] {
        const settings = this.readWorkspaceSettings();
        if (settings && settings['css.helper'] && settings['css.helper'].styleSheets) {
            return settings['css.helper'].styleSheets;
        }
        return [];
    }

    /**
     * 获取工作区根路径
     * @returns 工作区根路径
     */
    public getWorkspaceRoot(): string | undefined {
        return this.workspaceRoot;
    }
}
